package com.ifcar.app.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ifcar.app.api.dao.AccountApi;
import com.ifcar.app.api.dao.impl.AccountApiImpl;
import com.ifcar.app.util.EC;
import com.url.ajax.json.JSONException;
import com.url.ajax.json.JSONObject;

/**
 * 注册servlet
 * @author nxlixa
 *
 */
public class Register extends Base {
	
	private static final long serialVersionUID = 9009662647746201815L;

	/**
	 * 注册 api 服务入口
	 */
	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		req.setCharacterEncoding("UTF-8");
		
		String content = "";
		
		content = userRegister(req,resp);
		sendContent(resp, content, CONTEXT_TYPE);
		
		return;

	}	
	
	/**
	 * 注册
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	private String userRegister(ServletRequest request, ServletResponse response){

		String phone = request.getParameter("phone");
		String pwd = request.getParameter("pwd");
		String email = request.getParameter("email");
		
		AccountApi dao = new AccountApiImpl();
		JSONObject message = null;
		try {
			message = dao.register(phone, pwd, email);
		} catch (Exception e) {
			try {
				message.remove(EC.SUCCESS);
				message.put(EC.CODE, EC.CODE_SERVER_ERROR);
				message.put(EC.ERROR, EC.MSG_SERVER_ERROR);
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		
		return  message.toString();
	}
	
}
